package com.climber.spb_rabbitmq.spb_backqueue.controller;

import com.climber.spb_rabbitmq.spb_backqueue.config.RabbitMQConfig;
import com.climber.spb_rabbitmq.spb_backqueue.utils.MyCallBack;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;


@RestController
public class MessageController {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    private MyCallBack myCallBack;

    /**
     * 发布消息确认部分
     */
    /**
     * @todo @PostConstruct 会在依赖注入完成后被自动调用
     * 依赖注入 rabbitTemplate 之后再设置它的回调对象
     */

    @PostConstruct
    public void init() {

        rabbitTemplate.setConfirmCallback(myCallBack);
        /**
         * Mandatory
         * true：交换机无法将消息进行路由时，会将该消息返回给生产者
         * false：如果发现消息无法进行路由，则直接丢弃
         */
        rabbitTemplate.setMandatory(true);
//        rabbitTemplate.setMandatory(false);
        rabbitTemplate.setReturnsCallback(myCallBack);
    }
    //指定消息 id 为 1
    @GetMapping("sendMessageConfirm/{message}")
    public void sendMessageConfirm(@PathVariable String message) {
        CorrelationData correlationData1 = new CorrelationData("1");
        String routingKey = RabbitMQConfig.CONFIRM_ROUTINGKEY;
        rabbitTemplate.convertAndSend(RabbitMQConfig.CONFIRM_EXCHANGE_NAME,routingKey, routingKey+"=>"+message , correlationData1);
        System.out.printf("发送消息内容:%s\n", message);
        CorrelationData correlationData2 = new CorrelationData("2");
        routingKey = "key2";
        rabbitTemplate.convertAndSend(RabbitMQConfig.CONFIRM_EXCHANGE_NAME, routingKey, routingKey+"=>"+message, correlationData2);
        System.out.printf("发送消息内容:%s\n", message);
        CorrelationData correlationData3 = new CorrelationData("3");
        routingKey = RabbitMQConfig.CONFIRM_ROUTINGKEY;
        rabbitTemplate.convertAndSend("K", routingKey, routingKey+"=>"+message , correlationData3);
        System.out.printf("发送消息内容:%s\n", message);

    }

}